package com.finstone.data.spider.eshop.processor;

import java.util.*;

import com.sun.org.apache.bcel.internal.generic.Select;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.processor.PageProcessor;
import us.codecraft.webmagic.selector.Html;
import us.codecraft.webmagic.selector.Selectable;

import com.finstone.data.spider.eshop.service.impl.EShopGoodsDetailImageService;
import com.finstone.data.spider.eshop.service.impl.EShopGoodsDetailParamService;

@Component
public class EShopGoodsDetailProcessor implements PageProcessor {

	private final Logger logger = LoggerFactory.getLogger(getClass());

	private Site site = Site.me().setCycleRetryTimes(3).setTimeOut(30000);

	@Autowired
	private EShopGoodsDetailImageService eShopGoodsDetailImageService;

	@Autowired
	private EShopGoodsDetailParamService eShopGoodsDetailParamService;

	public Site getSite() {
		site.addHeader("Referer", "http://www.lenovo.com.cn/");
		site.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.101 Safari/537.36");
		return site;
	}

	public void process(Page page) {
		Html html = page.getHtml();

		String good_id = page.getRequest().getExtra("goods_id").toString();
		String dir_id = "1a60e7bf-49e3-493e-8fa3-ad907226d92e";
		String price = page.getRequest().getExtra("price").toString();
		String good_name = page.getRequest().getExtra("name").toString();
		String image_url = html.$("#bigim0 img", "src").toString();

		Map<String, String> basemap = new HashMap<String, String>();
		Random random = new Random();
		Integer goods_id = 201600000 + random.nextInt(99999);
		basemap.put("goods_id", good_id);
		basemap.put("goods_name", good_name);
		basemap.put("goods_dir_id", dir_id);
		basemap.put("real_id",goods_id.toString());
		Map<String, String> map = new HashMap<String, String>();

		map.put("id", good_id);
		map.put("dir_id", dir_id);
		map.put("url", image_url);
		map.put("real_id",goods_id.toString());

		basemap.put("goods_price", price);
		basemap.put("goods_image_url",image_url);

		page.putField("base", basemap);

		eShopGoodsDetailImageService.putTask(map);

		eShopGoodsDetailParamService.putTask(good_id);
	}
}